package com.manager;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class QuestUserInterfaceService extends Service {
	public static final String TAG = "QuestUserInterfaceService";
	public static final String BROADCAST_ACTION = "com.game.broadcast.updatedisplay";
	private final Handler handler = new Handler();
	Intent intent;
	boolean running = false;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/* Creates a new Intent with the BROADCAST_ACTION
	 * string as the Action. */
	@Override
	public void onCreate() {
		super.onCreate();
		intent = new Intent(BROADCAST_ACTION);
	}

	/* Sets the boolean running to true - to make sure the
	 * handler will keep posting. It then removes any existing
	 * callbacks to make sure we don't get any unwanted calls.
	 * After which the handler is told to call the sendUpdatesToUI
	 * method after one second.
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "QuestUserInterfaceService started.");
		running = true;
		handler.removeCallbacks(sendUpdatesToUI);
	    handler.postDelayed(sendUpdatesToUI, 0);
		return Service.START_NOT_STICKY;
	}
	
	/* If running is set to true it will call the updateUI method
	 * and do another post with a delay of one second.
	 */
	private Runnable sendUpdatesToUI = new Runnable() {
    	public void run() {
    		if (running) {
    			updateUI();
        	    handler.postDelayed(this, 4);
    		}
    	}
    };
    
    /* Updates the UI by putting extra data to the intent,
     * which is then sent to broadcast.
     */
    private void updateUI() {
    	intent.putExtra("characterName", "George Washington");
    	
    	sendBroadcast(intent);
    }
    
    /* If the service is destroyed then running will be set to false
     * to avoid any more callbacks.
     */
    @Override
    public void onDestroy() {
    	running = false;
    }   
}
